package com.example.demo.mq.producer;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;
import org.apache.activemq.ScheduledMessage;

import javax.jms.*;
import java.util.UUID;

public class DelayAndScheduleProducer {
    static String BROCKER_URL = "tcp://127.0.0.1:61616";
    static String QUEUE_NAME = "queue_delay";


    public static void main(String[] args) throws JMSException {
        // 1. 创建连接工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(BROCKER_URL);

        // 2. 获取连接 并启动
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        // 3. 创建session ,参数一：事务，参数二：签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4. 创建目的地,队列
        Queue queue = session.createQueue(QUEUE_NAME);
        // 5.创建消息生产者 类型为ActiveMQMessageProducer
        ActiveMQMessageProducer messageProducer = (ActiveMQMessageProducer) session.createProducer(queue);
        messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        // 6.通过 messageProducer 发送3条消息

        long delay = 1000 * 20;
        long period = 1000 * 2;
        int repeat = 3;

        for (int i = 1; i <= 3; i++) {
            TextMessage textMessage = session.createTextMessage("延迟消息 -> " + i);

            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
            textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
            // 发送消息，异步回调
            messageProducer.send(textMessage);

        }

        // 7.关闭资源
        messageProducer.close();
        session.close();
        connection.close();
    }
}
